package com.bawei.fuxi.ui.friends;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bawei.fuxi.R;
import com.bawei.fuxi.base.mvp.BaseFragment;
import com.bawei.fuxi.entity.ResultEntity;
import com.bawei.fuxi.entity.VideoEntity;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.HashMap;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 3．抖音fragment：
 （1）请求视频数据
 （2）上下翻页切换视频
 （3）多布局展示视频数据
 （4）转盘一直旋转
 （5）分享功能
 （6）点赞/收藏视频
 （7）关注功能
 （8）点击查看评论/发表评论
 （9）点击【全屏观看】切换全屏模式
 （10）点击【进入直播间】跳转到直播页面
 */
public class FriendsFragment extends BaseFragment<FriendsContract.IFriendsView,FriendsPresenter> implements FriendsContract.IFriendsView {
    private RecyclerView rv;
    private VideoAdapter mVideoAdapter;
    private DouYinLinearLayoutManager mDouYinLinearLayoutManager;
    private int currentPosition;//当前下标


    @Override
    public int bindLayout() {
        return R.layout.fragment_friends;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        rv = (RecyclerView) findViewById(R.id.rv);
        mVideoAdapter = new VideoAdapter();
        rv.setAdapter(mVideoAdapter);
        mDouYinLinearLayoutManager = new DouYinLinearLayoutManager(getContext());
        rv.setLayoutManager(mDouYinLinearLayoutManager);
        //自动播放视频
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //1:获得当前下标
                currentPosition = mDouYinLinearLayoutManager.findFirstVisibleItemPosition();
                //2:根据下标获得视频播放器
                StandardGSYVideoPlayer standardGSYVideoPlayer = (StandardGSYVideoPlayer) mVideoAdapter.getViewByPosition(currentPosition,R.id.gsy);
                //3:播放
                if(standardGSYVideoPlayer != null){
                    standardGSYVideoPlayer.startPlayLogic();
                }
            }
        });
        //item子控件的点击事件
        mVideoAdapter.addChildClickViewIds(R.id.iv_dianzan,R.id.iv_share,R.id.iv_add,R.id.ll_zhibo,R.id.ll_full,R.id.iv_comment,R.id.iv_send);
        mVideoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()){
                    case R.id.iv_dianzan://点赞
                        dianzan();
                        break;
                    case R.id.iv_share://分享
                        share();
                        break;
                    case R.id.iv_add://关注
                        guanzhu();
                        break;
                    case R.id.ll_zhibo://进入直播页面
                        zhibo();
                        break;
                    case R.id.ll_full://全屏观看
                        full();
                        break;
                    case R.id.iv_comment://查看评论
                        showComment();
                        break;
                    case R.id.iv_send://发表评论
                        sendComment();
                        break;
                }
            }
        });

    }

    private void sendComment() {
        String token = SPUtils.getInstance().getString("token");
        if (TextUtils.isEmpty(token)) {
            Toast.makeText(getActivity(), "去登陆", Toast.LENGTH_SHORT).show();
            ARouter.getInstance().build("/app/login").navigation();
        }else{//发表评论

        }


    }

    private void showComment() {

    }
    //全屏观看
    private void full() {
        StandardGSYVideoPlayer standardGSYVideoPlayer = (StandardGSYVideoPlayer) mVideoAdapter.getViewByPosition(currentPosition,R.id.gsy);
        standardGSYVideoPlayer.startWindowFullscreen(getContext(),true,true);

    }
    //点击进入直播间
    private void zhibo() {
        ARouter.getInstance().build("/app/zhibo")
                .withSerializable("video",mVideoAdapter.getData().get(currentPosition))
                .navigation();
    }

    private void guanzhu() {
        String token = SPUtils.getInstance().getString("token");
        if (TextUtils.isEmpty(token)) {
            Toast.makeText(getActivity(), "去登陆", Toast.LENGTH_SHORT).show();
            ARouter.getInstance().build("/app/login").navigation();
        }else{//关注
            String authname = mVideoAdapter.getData().get(currentPosition).getAuthname();
            HashMap<String, String> map = new HashMap<>();
            map.put("authname",authname);
            String json = new Gson().toJson(map);
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
            mPresenter.guanzhu(requestBody);

        }
    }

    private void share() {
        String token = SPUtils.getInstance().getString("token");
        if (TextUtils.isEmpty(token)) {
            Toast.makeText(getActivity(), "去登陆", Toast.LENGTH_SHORT).show();
            ARouter.getInstance().build("/app/login").navigation();

        }else{//分享

        }
    }

    private void dianzan() {
        String token = SPUtils.getInstance().getString("token");
        if (TextUtils.isEmpty(token)) {
            Toast.makeText(getActivity(), "去登陆", Toast.LENGTH_SHORT).show();
            ARouter.getInstance().build("/app/login").navigation();
        }else{//点赞
            int id = mVideoAdapter.getData().get(currentPosition).getId();//视频id
            mPresenter.dianzan(id);
        }
    }

    @Override
    public FriendsPresenter createPresenter() {
        return new FriendsPresenter();
    }

    @Override
    public void initData() {
        Log.d("ytx", "video0000: ");
        mPresenter.video(1,40);

    }

    @Override
    public void showVideo(VideoEntity videoEntity) {
        Toast.makeText(getActivity(), ""+videoEntity.getData().size(), Toast.LENGTH_SHORT).show();
        if(videoEntity != null && videoEntity.getCode() == 200){
            mVideoAdapter.getData().addAll(videoEntity.getData());
            mVideoAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showDianZan(ResultEntity resultEntity) {
        if(resultEntity != null && resultEntity.getCode() == 200){
            Toast.makeText(getActivity(), "点赞成功", Toast.LENGTH_SHORT).show();
            ImageView ivDianzan = (ImageView) mVideoAdapter.getViewByPosition(currentPosition,R.id.iv_dianzan);
            ivDianzan.setImageResource(R.drawable.ic_xihuanred);//图片变红
            mVideoAdapter.getData().get(currentPosition).setDianzan(1);//数据更新
         }
    }

    @Override
    public void showGuanZhu(ResultEntity resultEntity) {
        if(resultEntity != null && resultEntity.getCode() == 200){
            Toast.makeText(getActivity(), "关注成功", Toast.LENGTH_SHORT).show();
            ImageView ivAdd = (ImageView) mVideoAdapter.getViewByPosition(currentPosition,R.id.iv_add);
            ivAdd.setVisibility(View.GONE);//隐藏
            mVideoAdapter.getData().get(currentPosition).setGuanzhu(1);//数据更新
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }
}